<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row" v-privilege="'goods:query'">

      <a-form-item label="角色名称" class="smart-query-form-item">
        <a-input-search style="width: 300px" v-model:value="queryForm.roleName" placeholder="请输入角色名称" enter-button="选择"
          @search="openRoleTable" />
      </a-form-item>
      <a-form-item label="应用名称" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.searchWord" />
      </a-form-item>

      <a-form-item class="smart-query-form-item">
        <a-button-group>
          <a-button type="primary" @click="onSearch" v-privilege="'goods:query'">
            <template #icon>
              <ReloadOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery" v-privilege="'goods:query'">
            <template #icon>
              <SearchOutlined />
            </template>
            重置
          </a-button>
        </a-button-group>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="add" type="primary" v-privilege="'goods:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>

        <a-button @click="confirmBatchDelete" danger :disabled="selectedRowKeyList.length === 0"
          v-privilege="'goods:batchDelete'">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :pagination="false"
      :showSorterTooltip="false" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
      @change="onChange">
      <template #bodyCell="{ text, record, column }">
        <template v-if="column.dataIndex === 'iconBase64'">
          <img :src="record.iconBase64" alt="" style="width: 40px;">
        </template>
        <template v-if="column.dataIndex === 'visible'">
          {{record.visible===1?'显示':'隐藏'}}
        </template>
        <template v-if="column.dataIndex === 'category'">
          {{
            FindList.filter(i => i.value === record.category).length ? FindList.filter(i => i.value ===
              record.category)[0].label : ''
          }}
        </template>
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="visibleChange(record)" type="link">{{record.visible===1?'隐藏':'显示'}}</a-button>
            <a-button @click="deleteGoods(record)" danger type="link">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize" v-model:current="queryForm.pageNumber" v-model:pageSize="queryForm.pageSize"
        :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
  </a-card>
  <RoleSelection ref="roleTableRef" v-model:value="selectedRowKeyList" @change="roleTableChange"></RoleSelection>
  <AppTable ref="appTableRef" v-model:value="appSelectedRowKeyList" @change="appTableChange"></AppTable>
</template>
<script setup>
import RoleSelection from '/@/components/roleSelection/index.vue'
import AppTable from '/@/views/permissions/resources/components/app-table.vue'
// import GoodsFormModal from './components/goods-form-modal.vue';
import { reactive, ref, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { goodsApi } from '/@/api/business/goods/goods-api';
import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import CategoryTree from '/@/components/business/category-tree-select/index.vue';
import { CATEGORY_TYPE_ENUM } from '/@/constants/business/erp/category-const';
import { smartSentry } from '/@/lib/smart-sentry';
import TableOperator from '/@/components/support/table-operator/index.vue';
import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
import { GOODS_STATUS_ENUM } from '/@/constants/business/erp/goods-const';
import DictSelect from '/@/components/support/dict-select/index.vue';
import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue';
import { FILE_FOLDER_TYPE_ENUM } from '/@/constants/support/file-const.js';
import FileUpload from '/@/components/support/file-upload/index.vue';
import _ from 'lodash';
import { permissionsApi } from '/@/api/access/permissions'
import { applicationManagementApi } from '/@/api/system/applicationManagement-api'
import { useRoute } from 'vue-router';

// ---------------------------- 表格列 ----------------------------

const columns = ref([
  {
    title: '角色名称',
    dataIndex: 'roleName',
  },
  {
    title: '图标',
    dataIndex: 'iconBase64',
  },
  {
    title: '应用名称',
    dataIndex: 'appName',
    sorter: true
  },
  {
    title: '分类',
    dataIndex: 'category',
  },
  {
    title: '状态',
    dataIndex: 'visible',
    sorter: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 100,
  },
]);

// ---------------------------- 查询数据表单和方法 ----------------------------

const queryFormState = {
  roleName: '',
  roleId: '',
  pageNumber: 1,
  pageSize: 10,
};
// 查询表单form
const queryForm = reactive(_.cloneDeep(queryFormState));
// 表格加载loading
const tableLoading = ref(false);
// 表格数据
const tableData = ref([]);
// 总数
const total = ref(0);

// 重置查询条件
function resetQuery() {
  let pageSize = queryForm.pageSize;
  Object.assign(queryForm, _.cloneDeep(queryFormState));
  queryForm.pageSize = pageSize;
  queryData();
}

// 搜索
function onSearch() {
  queryForm.pageNumber = 1;
  queryData();
}

// 查询数据
async function queryData() {
  tableLoading.value = true;
  try {
    let queryResult = await permissionsApi.getFetch(queryForm);

    tableData.value = queryResult.data.rows;
    total.value = queryResult.data.records;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

const route = useRoute();
onMounted(() => {
  if (route.query.roleId) {
    queryForm.roleId = route.query.roleId;
    queryForm.roleName = route.query.roleName;
  }
  getFindList();
  queryData();
});
// ---------------------------- 角色选择 ----------------------------
const roleSelectedRowKeyList = ref([]);
const roleTableRef = ref(null)
function openRoleTable() {
  roleTableRef.value.showModal();
}
function roleTableChange(records) {
  queryForm.roleName = selectedRowKeyList.value[0];
  queryForm.roleId = records[0].id
  queryData();
}
// ---------------------------- 新增 ----------------------------
const appSelectedRowKeyList = ref([]);
const appTableRef = ref(null);
function appTableChange(records) {
  if (queryForm.roleId) {
    permissionsApi.add({
      appId:records[0].id,
      appName:records[0].appName,
      roleId:queryForm.roleId
    }).then(res => {
      if(res.code === 0){
        message.success('成功!')
        queryData();
      }
    })
  }
  
}
function add() {
  if (queryForm.roleId) {
    appTableRef.value.showModal();
  }
}
// ---------------------------- 修改 ----------------------------

function visibleChange(data) {
  permissionsApi.updateVisible({
    id:data.id,
    visible:data.visible===1?0:1
  }).then(res=>{
    if(res.code === 0){
        message.success('成功!')
        queryData();
      }
  })
}
// ---------------------------- 单个删除 ----------------------------

function deleteGoods(goodsData) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      singleDelete(goodsData);
    },
    cancelText: '取消',
    onCancel() { },
  });
}

async function singleDelete(goodsData) {
  try {
    SmartLoading.show();
    await permissionsApi.delete({ids:goodsData.id});
    message.success('删除成功');
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

// ---------------------------- 批量删除 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([]);

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys;
}

// 批量删除
function confirmBatchDelete() {
  Modal.confirm({
    title: '提示',
    content: '确定要删除选中吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      batchDelete();
    },
    cancelText: '取消',
    onCancel() { },
  });
}

async function batchDelete() {
  try {
    SmartLoading.show();
    await permissionsApi.delete({ids:selectedRowKeyList.value.join(',')});
    message.success('删除成功');
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}



// 获取分类下拉
const FindList = ref([])
async function getFindList() {
  try {
    let res = await applicationManagementApi.queryFindList();
    FindList.value = res.data.map(item => {
      return {
        label: item.name,
        value: item.id
      }
    })
    FindList.value.unshift({ label: 'ALL', value: '' })
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
  }
}
</script>